﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace MaciejGrabek.WP7.Services.Phone.Serialization
{
    public static class JsonSerializationHelper
    {
        public static string Serialize<T>(T item)
        {
            MemoryStream ms = new MemoryStream();
            DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(T));
            s.WriteObject(ms, item);
            byte[] json = ms.ToArray();
            ms.Close();
            return Encoding.UTF8.GetString(json, 0, json.Length);
        }

        public static T Deserialize<T>(string itemString)
        {
            byte[] data = Encoding.UTF8.GetBytes(itemString);
            MemoryStream memStream = new MemoryStream(data);
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            T item = (T)serializer.ReadObject(memStream);
            return item;
        }

        public static T Deserialize<T>(Stream jsonStream)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            T item = (T)serializer.ReadObject(jsonStream);
            return item;
        }
    }
}
